// utils
const dayjs = require("dayjs")

// modules
const response = require('../utils/methods/response.js')
const ArticleModule = require('../models/tableModels/articleModule.js')

// methods
const jsonFormat = require('../utils/methods/jsonFormat')
const splitParams = require('../utils/methods/splitParams')

// 文章控制器
const articleController = {
    // 新增文章
    newArticle: async ({ body }, res) => {
        try {
            // 插入数据
            const insertData = {
                ...body,
                createdTime: dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss'),
                likeCount: 0,
                viewCount: 0,
                articlePictureList: JSON.stringify(body.articlePictureList)
            }
            // 新增文章
            const articleInsertResult = await ArticleModule.insert(insertData)
            articleInsertResult ? response.success(res) : response.fail(res, '插入失败！')
        } catch(err) {
            response.error(res, err)
        }
    },
    // 获取文章列表
    articleList: async ({ body }, res) => {
        try {
            // 参数拆分
            const { pageParams, otherParams } = splitParams(body)
            // 响应列表数据、数据总条数
            let responseList, total
            // 如果没有指定字段，则查询所有
            if (!otherParams) {
                // 获取表数据总条数
                total = (await ArticleModule.knexAllCount())[0]['count(*)']
                // 分页查询
                responseList = await ArticleModule.knexAllDescLimitSelect(pageParams, 'articleId')
            } else {
                // 取出参数的个数和参数值
                const { paramsLength, paramsValue } = otherParams
                // 如果参数值有文章标题，模糊匹配查询文章标题
                if (Object.prototype.hasOwnProperty.call(paramsValue, 'articleTitle')) {
                    // 如果只有 articleTitle 字段，则直接模糊匹配
                    if (paramsLength === 1) {
                        responseList = await ArticleModule.knexLikeSelectLimitDesc('articleTitle', paramsValue.articleTitle, pageParams, 'articleId')
                        total = (await ArticleModule.knexLikeSelect('articleTitle', paramsValue.articleTitle)).length
                    } else {
                        // 如果还有其他字段，则合并查询
                        const newSearchParams = jsonFormat(paramsValue)
                        delete newSearchParams.articleTitle
                        responseList = await ArticleModule.knexLikeAndOtherSelectLimitDesc('articleTitle', paramsValue.articleTitle, newSearchParams, pageParams, 'articleId')
                        total = (await ArticleModule.knexLikeAndOtherSelect('articleTitle', paramsValue.articleTitle, newSearchParams)).length
                    }
                } else {
                    // 无标题直接查询其他
                    responseList = await ArticleModule.knexSelectFiledRowLimitDesc(paramsValue, pageParams, 'articleId')
                    total = (await ArticleModule.knexSelectFiledRow(paramsValue)).length
                }
            }
            // 响应数据
            const responseData = {
                total,
                // 处理时间格式
                list: responseList.length ? jsonFormat(responseList).map(item => {
                    item.articlePictureList = JSON.parse(item.articlePictureList)
                    item.createdTime = dayjs(item.createdTime).format('YYYY-MM-DD HH:mm:ss')
                    return item
                }) : []
            }
            response.success(res, responseData)
        } catch(err) {
            response.error(res, err)
        }
    },
    // 删除文章
    deleteArticle: async ({ query }, res) => {
        try {
            // 删除文章
            const deleteResult = await ArticleModule.delete({ articleId: query.articleId })
            deleteResult ? response.success(res) : response.fail(res, '删除失败！请重试')
        } catch(err) {
            response.error(res, err)
        }
    },
    // 更新文章状态
    updateArticleStatus: async ({ body }, res) => {
        try {
            // 获取文章 id 和 状态
            const { articleId, releaseStatus } = jsonFormat(body)
            // 更新状态
            const updateResult = await ArticleModule.update({ articleId }, { releaseStatus })
            // 判断更新结果
            updateResult ? response.success(res) : response.fail(res, '更新失败！请重试')
        } catch(err) {
            response.error(res, err)
        }
    },
    // 更新文章
    updateArticle: async ({ body }, res) => {
        try {
            // 获取文章 id
            const { articleId, articlePictureList } = jsonFormat(body)
            const updateData = {
                ...jsonFormat(body),
                articlePictureList: JSON.stringify(articlePictureList)
            }
            // 更新状态
            const updateResult = await ArticleModule.update({ articleId }, updateData)
            // 判断更新结果
            updateResult ? response.success(res) : response.fail(res, '更新失败！请重试')
        } catch(err) {
            response.error(res, err)
        }
    },
    // 文章详情
    articleDetail: async ({ query }, res) => {
        try {
            // 获取文章详情
            const articleDetailResult = (await ArticleModule.knexSelectFiledRow({ articleId: query.articleId }))[0]
            // 响应数据
            const responseData = {
                ...articleDetailResult,
                articlePictureList: JSON.parse(articleDetailResult.articlePictureList)
            }
            articleDetailResult ? response.success(res, responseData) : response.fail(res, '获取失败！请重试')
        } catch(err) {
            response.error(res, err)
        }
    }
}

module.exports = articleController
